package com.example.admin_oa.dubbo;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.admin_oa.model.mapper.SysUserMapper;
import com.example.admin_oa.model.mapper.SysUserRoleMapper;
import com.example.admin_oa.model.service.SysUserService;
import com.example.admin_oa.utils.StringUtil;
import com.example.comment_oa.dubbo.SysUserDubbo;
import com.example.comment_oa.pojos.SysUser;
import com.example.comment_oa.pojos.SysUserRole;
import org.apache.dubbo.config.annotation.DubboService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@DubboService(version = "1.0.0",protocol = "${dubbo.protocol.id}",
        application = "${dubbo.application.id}",registry = "${dubbo.registry.id}",
        timeout = 3000)
public class SysUserDubboImpl implements SysUserDubbo {
    @Resource
    SysUserMapper sysUserMapper;
    @Resource
    SysUserService sysUserService;
    @Resource
    SysUserRoleMapper sysUserRoleMapper;

    @Override
    public SysUser login(String username, String userPassword) {
        return sysUserService.login(username,userPassword);
    }

    @Override
    public int insert(SysUser sysUser) {
        QueryWrapper<SysUser> wrapper=new QueryWrapper<>();
        wrapper.orderByDesc("user_id");
        wrapper.last("limit 1");
        SysUser sysUser1 = sysUserMapper.selectOne(wrapper);//取出最新的一条
        String substring = sysUser1.getUserNo().substring(4);
        int i = Integer.parseInt(substring);
        String s = Integer.toString(++i);
        sysUser.setUserNo("USER"+s);
        sysUser.setUserPassword(StringUtil.md5("123456"));
        int insert = sysUserMapper.insert(sysUser);//用户表新增
        SysUser sysUser2 = sysUserMapper.selectOne(wrapper);//取出最新的一条
        List<SysUserRole> sysUserRoleList=new ArrayList<>();
        sysUserRoleList.add(new SysUserRole(sysUser2.getUserId(),2));//默认角色为普通员工
        sysUserRoleMapper.insertBatch(sysUserRoleList);
        return insert;
    }

    @Override
    public int update(SysUser sysUser) {
        sysUser.setUserPassword(StringUtil.md5(sysUser.getUserPassword()));
        return sysUserMapper.updateById(sysUser);
    }

    @Override
    public int delete(SysUser sysUser) {
        sysUser.setUserState(1);
        return sysUserMapper.updateById(sysUser);
    }

    @Override
    public Set<String> findUserPermissionByid(int userId) {
        return sysUserMapper.findUserPermissionByid(userId);
    }
}
